package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.ExcelSubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import java.util.Date;

/**
 * @author alan
 */
public class SubjectExcelListener extends AnalysisEventListener<ExcelSubjectData> {

    private EduSubjectService eduSubjectService;
    private int sort = 1;

    public SubjectExcelListener(EduSubjectService eduSubjectService, int sort) {
        this.eduSubjectService = eduSubjectService;
        this.sort = sort;
    }

    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    /**
     * 逐行读取表
     *
     * @param excelSubjectData
     * @param analysisContext
     */
    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {
        if (ObjectUtils.isNull(excelSubjectData)) {
            throw new GuliException(20001, "添加失败");
        }
        saveDate(excelSubjectData, sort);
        sort++;
    }

    private void saveDate(ExcelSubjectData data, int sort) {

        EduSubject dbData =
                eduSubjectService.getOne(Wrappers.<EduSubject>lambdaQuery().eq(EduSubject::getTitle, data.getOneSubjectName()), false);
        Date now = new Date();

        if (ObjectUtils.isNull(dbData)) {
            EduSubject pEduSubject = new EduSubject();
            pEduSubject.setSort(eduSubjectService.getNextSort("0"))
                    .setParentId("0")
                    .setTitle(data.getOneSubjectName())
                    .setGmtCreate(now);
            eduSubjectService.save(pEduSubject);

            EduSubject eduSubject = new EduSubject();
            eduSubject.setParentId(pEduSubject.getId())
                    .setGmtCreate(now)
                    .setTitle(data.getTwoSubjectName())
                    .setSort(eduSubjectService.getNextSort(pEduSubject.getId()));
            eduSubjectService.save(eduSubject);

        } else {
            EduSubject eduSubject = new EduSubject();
            eduSubject.setParentId(dbData.getId())
                    .setGmtCreate(now)
                    .setTitle(data.getTwoSubjectName())
                    .setSort(eduSubjectService.getNextSort(dbData.getId()));
            eduSubjectService.save(eduSubject);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
